import { _decorator, Component, Node } from 'cc';
import ScrollHelper from '../ScrollHelper';
import { MultiMsgMgr } from './MultiMsgMgr';
import { RoomItem } from './RoomItem';
import { tween } from 'cc';
import UtilTool from '../../tools/UtilTool';
import { find } from 'cc';
import { UITransform } from 'cc';
import { ScrollView } from 'cc';
import { RigidBody } from 'cc';
import { PhysicsSystem } from 'cc';
import { showTip } from '../../tools/PopuUp';
import { App } from '../../App';
const { ccclass, property } = _decorator;

let PAGE_DEFAULT_SIZE = 30; // 默认每页30条
let DEFAULT_UPDATE_TIME = 15; // 默认15秒更新一次

/**
 * 房间列表刷新控件
 */
@ccclass('RoomListCtrl')
export class RoomListCtrl extends Component {

    @property(Node)
    empty_room: Node= null

    private itemNum = 6
    // [listData]列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 
    // 记录数据
    private configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : PAGE_DEFAULT_SIZE/2}
    private recodeData = null
    
    contentNode : Node = null;

    scrollHelper : ScrollHelper = null;

    roomType = 0

    passUpdateTime = 0 // 更新时间

    start() {

        UtilTool.setSize(this.node, 3, [0, 2])
        UtilTool.setSize(this.node.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(find("view/content",this.node), 3, [0, 2])
    }

    onBtnRefresh() {
        this.refresh(true)
    }

    // 重新拉取数据
    init(roomType) {
        this.scrollHelper = this.node.getComponent(ScrollHelper);
        this.contentNode = find("view/content",this.node)
        
        this.roomType = roomType
        this.refresh()
    }

    // 发送测试数据
    sendGetTestData(roomType, page, pageSize) : Promise<any> {

        return new Promise((resolve, reject) => {

            let data = {
                list : []
            }

            if(page >= 3) {
                resolve(data) // 大于等于3页就不再请求数据（即一共只有30个）
                return
            }


            pageSize = 2
            for(let i = 0; i < pageSize; i++) {
                let index = page * pageSize + i + 1
                let item = {
                    canWatch : true,
                    roomId : "test00" + index,
                    gameType : 0,
                    status : 1,
                    maxPlayer :3,
                    currentPlayerNum: 2,
                    playAmount : 100,
                    havePassword : false,
                }
                data.list.push(item)
            }

            resolve(data)

        })

    }

    // 刷新当前列表
    refresh(isClick = false) {
        UtilTool.printLog("test refresh")

        this.configData.listData = [] // 清空数据
        this.configData.currPage = 0

        this.contentNode.getComponent(UITransform).height = this.contentNode.parent.getComponent(UITransform).height
        this.node.getComponent(ScrollView).scrollToTop(0.1)

        tween(this.node).delay(0.2).call(() => {
            if (this.configData.isLoading) {
                return
            }

            this.contentNode.removeAllChildren()
            this.reqData(true, 0, isClick) // 默认刷新第一页
        }).start()
        
    }

    // 设置搜索的数据
    setSearchDataList(roomId) {
        MultiMsgMgr.getInstance().sendSearchRoomList(this.roomType, roomId)
        .then((data) => {
            UtilTool.printLog("test search room", data);

            if(data.list.length == 0) {
                showTip(App.language.getLanguageLab(2008)) // 未找到该房间
            } else {

                this.configData.listData = [] // 清空数据
                this.configData.currPage = 0
        
                this.contentNode.getComponent(UITransform).height = this.contentNode.parent.getComponent(UITransform).height
                this.node.getComponent(ScrollView).scrollToTop(0.1)
                
                tween(this.node).delay(0.2).call(() => {
                    this.contentNode.removeAllChildren()
                    this.setRoomItemNodeList(data, true, 0)
                }).start()
            }

        })
    }

    // 默认为当前页的下一页
    reqData(isInit=true, page, isClick = false) {
        this.configData.isLoading = true

        this.passUpdateTime = 0

        MultiMsgMgr.getInstance().sendGetRoomList(this.roomType, page, PAGE_DEFAULT_SIZE)
        // this.sendGetTestData(this.roomType, page, PAGE_DEFAULT_SIZE) // 测试数据
        .then((data) => {
            UtilTool.printLog("test room list", data);
            if (isClick) {
                showTip(App.language.getLanguageLab(167))
            }
            this.setRoomItemNodeList(data, isInit, page)
        })
    }

    // 设置房间列表数据
    setRoomItemNodeList(data, isInit, page) {

        // 修改data的list为一行两个的数据
        let dataList = {
            "list" : []
        }

        let maxLineCount = Math.ceil(data.list.length / 2)
        for(let i=0; i<maxLineCount; i++) {
            let lineData = []
            for(let j=0; j<2; j++) {
                let index = i * 2 + j
                if(index < data.list.length) {
                    lineData.push(data.list[index])
                }
            }
            dataList.list.push(lineData)
        }

        UtilTool.printLog("test reqData", page, dataList)

        this.recodeData= dataList
        this.configData.currPage = page + 1
        this.configData.isLoading = false

        dataList.list.forEach(element => {
            this.configData.listData.push(element)
        });
        if (dataList.list==null || dataList.list.length < this.configData.pageSize) {
            this.configData.loadOver = true
        }
        this.empty_room.active = this.configData.listData.length<=0?true:false

        if (dataList.list.length>0) {
            let param = {
                init:isInit, 
                data:this.configData.listData,
                itemNum:this.itemNum,
                itemFun: (obj,idx,objIdx)=>{
                    this.refreshItem(obj,idx,objIdx)
                },
                endFun:()=>{
                    this.OnScrollEnd()
                }
            }

            this.scrollHelper.setData(param)
        }

    }

    // 每隔一段时间刷新一次
    update(dt) {

        this.passUpdateTime += dt

        if(this.passUpdateTime > DEFAULT_UPDATE_TIME) {
            this.passUpdateTime = 0

            this.refresh()
        }

    }

    /**
     * 刷新itemnode数据
     * @param obj 
     * @param idx 
     * @param objIdx 
     * // obj lineitem 一个item有两个的数据
     * @returns 
     */
    refreshItem(obj,idx,objIdx) {
        
        if (this.configData.listData.length <= 0) {
            return
        }

        let data = this.configData.listData[idx]
        // obj.dataId = itemData.id

        // 设置一行两个的数据
        for(let i=0; i<obj.children.length; i++) {
            let itemNode = obj.children[i]
            let itemData = data[i]
            let itemCtrl : RoomItem = itemNode.getComponent(RoomItem)
            if(itemData) {
                itemCtrl.initData(itemData, this.roomType)
            } else {
                itemCtrl.setHide()
            }
        }

    }

    // 滚动视图滑到底部回调
    OnScrollEnd() {
        // let typeStr = Object.keys(ScrollView.EventType)[eventType]
        // UtilTool.printLog("test onScroll", eventType, typeStr)

        if (this.configData.isLoading) {
            return
        }
        if (this.configData.loadOver) {
            return
        }

        this.reqData(false, this.configData.currPage)
    }

}

